package com.kodin.polyfit;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.kodin.webview.SplashActivity;

import org.apache.commons.math3.analysis.ParametricUnivariateFunction;
import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math3.fitting.SimpleCurveFitter;
import org.apache.commons.math3.fitting.WeightedObservedPoints;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class CurveFit {

    public static Map<String, Object> curveFit(double[][] data, int guessNum) {
        ParametricUnivariateFunction function = new PolynomialFunction.Parametric();/*多项式函数*/
        double[] guess = new double[guessNum]; /*猜测值 依次为 常数项、1次项、二次项*/
        for (int num = 0; num < guessNum; num++) {
            guess[num] = num + 1;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("best", null);
        map.put("log", null);
        if (data.length < guessNum) {
            return map;
        }
        // 初始化拟合
        SimpleCurveFitter curveFitter = SimpleCurveFitter.create(function, guess);

        // 添加数据点
        WeightedObservedPoints observedPoints = new WeightedObservedPoints();
        for (double[] point : data) {
            observedPoints.add(point[0], point[1]);
        }
        /*
         * best 为拟合结果
         * 依次为 常数项、1次项、二次项
         * 对应 y = a + bx + cx^2 中的 a, b, c
         * */
        double[] best = curveFitter.fit(observedPoints.toList());
        LogUtils.e("best:" + GsonUtils.toJson(best));
        map.put("best", best);
        /*
         * 根据拟合结果重新计算
         * */
        List<double[]> fitData = new ArrayList<>();
        String cha = "";
        for (double[] datum : data) {
            double x = datum[0];
            double y = 0;
            for (int j = 0; j < best.length; j++) {
                y += best[j] * Math.pow(x, j);// y = a + bx + cx^2
            }
            double[] xy = {x, y};
            fitData.add(xy);
            cha += String.format("x=%.0f 计算后:%.2fum 原始Y:%.2fum 差:%.2fum 偏差:%.2f%%\n", x, y / 10, datum[1] / 10, (y - datum[1]) / 10, 100 * (y - datum[1]) / datum[1]);
        }
        map.put("log", cha);
        LogUtils.e(cha);
        return map;
    }

    public static double fitRealByBest(double[] best, double x) {
        double re = 0;
        for (int j = 0; j < best.length; j++) {
            re += best[j] * Math.pow(x, j);// y = a + bx + cx^2
        }
        return re;
    }

    public static Result curveFitReal(double[][] data, int guessNum) {
        ParametricUnivariateFunction function = new PolynomialFunction.Parametric();/*多项式函数*/
        double[] guess = new double[guessNum]; /*猜测值 依次为 常数项、1次项、二次项*/
        for (int num = 0; num < guessNum; num++) {
            guess[num] = num + 1;
        }
        // 初始化拟合
        SimpleCurveFitter curveFitter = SimpleCurveFitter.create(function, guess);

        // 添加数据点
        WeightedObservedPoints observedPoints = new WeightedObservedPoints();
        for (double[] point : data) {
            observedPoints.add(point[0], point[1]);
        }
        /*
         * best 为拟合结果
         * 依次为 常数项、1次项、二次项
         * 对应 y = a + bx + cx^2 中的 a, b, c
         * */
        double[] best = curveFitter.fit(observedPoints.toList());
        LogUtils.e("best:" + GsonUtils.toJson(best));
        /*
         * 根据拟合结果重新计算
         * */
        List<double[]> fitData = new ArrayList<>();
        String cha = "";
        for (double[] datum : data) {
            double x = datum[0];
            double y = 0;
            for (int j = 0; j < best.length; j++) {
                y += best[j] * Math.pow(x, j);// y = a + bx + cx^2
            }
            double[] xy = {x, y};
            fitData.add(xy);
            cha += String.format("x=%.0f 计算后:%.2fum 原始Y:%.2fum 差:%.2fum 偏差:%.2f%%\n", x, y / 10, datum[1] / 10, (y - datum[1]) / 10, 100 * (y - datum[1]) / datum[1]);
        }
        LogUtils.e(cha);
        StringBuilder func = new StringBuilder();
        func.append(data.length + "使用数据点 ");
        func.append((guess.length - 1) + "阶函数 f(x) =");
        func.append(best[0] > 0 ? " " : " - ");
        func.append(Math.abs(best[0]));
        for (int j = 1; j < guess.length; j++) {
            func.append(best[j] > 0 ? " + " : " - ");
            func.append(Math.abs(best[j]));
            func.append("x^" + j);
        }
        func.append("\n");
        double[][] tar = fitData.stream().toArray(double[][]::new);
        return new Result(data, tar, func.toString() + cha, best);
    }


    /**
     * 求解多项式
     * y = a + bx + cx^2
     * 使用提供的data数据 模拟guessNum多项式 带入real数据验证误差
     *
     * @param data
     * @param guessNum
     * @param real
     * @return
     */
    public static Result curveFit(double[][] data, int guessNum, double[][] real) {
        ParametricUnivariateFunction function = new PolynomialFunction.Parametric();/*多项式函数*/
        double[] guess = new double[guessNum]; /*猜测值 依次为 常数项、1次项、二次项*/
        for (int num = 0; num < guessNum; num++) {
            guess[num] = num + 1;
        }
        // 初始化拟合
        SimpleCurveFitter curveFitter = SimpleCurveFitter.create(function, guess);

        // 添加数据点
        WeightedObservedPoints observedPoints = new WeightedObservedPoints();
        for (double[] point : data) {
            observedPoints.add(point[0], point[1]);
        }
        /*
         * best 为拟合结果
         * 依次为 常数项、1次项、二次项
         * 对应 y = a + bx + cx^2 中的 a, b, c
         * */
        double[] best = curveFitter.fit(observedPoints.toList());
        LogUtils.e(GsonUtils.toJson(best));
        /*
         * 根据拟合结果重新计算
         * */
        List<double[]> fitData = new ArrayList<>();
        String cha = "";
        for (double[] datum : real) {
            double x = datum[0];
            double y = 0;
            for (int j = 0; j < best.length; j++) {
                y += best[j] * Math.pow(x, j);// y = a + bx + cx^2
            }
            double[] xy = {x, y};
            fitData.add(xy);
            String flag = "未用";
            for (double[] da : data) {
                double xT = da[0];
                if (x == xT) {
                    flag = "已用";
                    break;
                }
            }
            cha += String.format("%s x=%.0f 计算后:%.2fum 原始Y:%.2fum 差:%.2fum 偏差:%.2f%%\n", flag, x, y / 10, datum[1] / 10, (y - datum[1]) / 10, 100 * (y - datum[1]) / datum[1]);
        }
        LogUtils.e(cha);
        StringBuilder func = new StringBuilder();
        func.append(data.length + "使用数据点 ");
        func.append((guess.length - 1) + "阶函数 f(x) =");
        func.append(best[0] > 0 ? " " : " - ");
        func.append(Math.abs(best[0]));
        for (int j = 1; j < guess.length; j++) {
            func.append(best[j] > 0 ? " + " : " - ");
            func.append(Math.abs(best[j]));
            func.append("x^" + j);
        }
        func.append("\n");
        double[][] tar = fitData.stream().toArray(double[][]::new);
        return new Result(data, tar, func.toString() + cha, best);
    }

    /**
     * 求解自定义多项式函数
     *
     * @param scatters
     * @return
     */
    public static Result customizeFuncFit(double[][] scatters) {
        ParametricUnivariateFunction function = new MyFunction();/*多项式函数*/
        double[] guess = {1, 1, 1, 1}; /*猜测值 依次为 a b c d 。必须和 gradient 方法返回数组对应。如果不知道都设置为 1*/

        // 初始化拟合
        SimpleCurveFitter curveFitter = SimpleCurveFitter.create(function, guess);

        // 添加数据点
        WeightedObservedPoints observedPoints = new WeightedObservedPoints();
        for (double[] point : scatters) {
            observedPoints.add(point[0], point[1]);
        }

        /*
         * best 为拟合结果 对应 a b c d
         * 可能会出现无法拟合的情况
         * 需要合理设置初始值
         * */
        double[] best = curveFitter.fit(observedPoints.toList());
        double a = best[0];
        double b = best[1];
        double c = best[2];
        double d = best[3];

        // 根据拟合结果生成拟合曲线散点
        List<double[]> fitData = new ArrayList<>();
        for (double[] datum : scatters) {
            double x = datum[0];
            double y = function.value(x, a, b, c, d);
            double[] xy = {x, y};
            fitData.add(xy);
        }

        // f(x) = d + ((a - d) / (1 + Math.pow(x / c, b)))
        StringBuilder func = new StringBuilder();
        func.append("f(x) =");
        func.append(d > 0 ? " " : " - ");
        func.append(Math.abs(d));
        func.append(" ((");
        func.append(a > 0 ? "" : "-");
        func.append(Math.abs(a));
        func.append(d > 0 ? " - " : " + ");
        func.append(Math.abs(d));
        func.append(" / (1 + ");
        func.append("(x / ");
        func.append(c > 0 ? "" : " - ");
        func.append(Math.abs(c));
        func.append(") ^ ");
        func.append(b > 0 ? " " : " - ");
        func.append(Math.abs(b));

        return new Result(scatters, fitData.stream().toArray(double[][]::new), func.toString(), best);
    }


}
